﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 异步更新窗体2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private async void button1_Click(object sender, EventArgs e)
        {
            // 启动异步任务  
            await Task.Run(() => LongRunningOperation());

            // 确保下面的代码在UI线程上运行  
            this.Invoke(new Action(() =>
            {
                for (int i = 0; i < 100; i++)
                {
                    System.Threading.Thread.Sleep(500);
                    // 更新窗体控件的代码  
                    label1.Text = $"运行进度:{i + 1}";
                    progressBar1.Value = i + 1;
                }

            }));
        }

        private void LongRunningOperation()
        {
            // 模拟长时间运行的任务  
            System.Threading.Thread.Sleep(5000);
        }
    }
}
